package com.sunwayworld.basemodule.business.outsource.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.business.outsource.bean.LimsOutsourceApplyBean;
import com.sunwayworld.basemodule.business.outsource.service.LimsOutsourceApplyService;
import com.sunwayworld.basemodule.business.outsourcers.bean.LimsOutsourcersProductMainBean;
import com.sunwayworld.basemodule.business.outsourcers.service.LimsOutsourcersProductMainService;
import com.sunwayworld.basemodule.business.outsourcers.service.LimsOutsourcersService;
import com.sunwayworld.basemodule.coredata.product.service.LimsProductMainService;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.NumberUtils;
import com.sunwayworld.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.business.outsource.dao.LimsOutsourceSampleDao;
import com.sunwayworld.basemodule.business.outsource.bean.LimsOutsourceSampleBean;
import com.sunwayworld.basemodule.business.outsource.service.LimsOutsourceSampleService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsOutsourceSampleServiceImpl implements LimsOutsourceSampleService {

    @Autowired
    private LimsOutsourceSampleDao limsOutsourceSampleDao;

    @Autowired
    private LimsOutsourceApplyService limsOutsourceApplyService;

    @Autowired
    private LimsOutsourcersProductMainService limsOutsourcersProductMainService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsOutsourceSampleDao getDao() {
        return limsOutsourceSampleDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsOutsourceSampleBean fromBean = jsonWrapper.parseUnique(LimsOutsourceSampleBean.class);

        String productids = fromBean.getExt$Item("productids");
        if (StringUtils.isBlank(productids)) {
            fromBean.setId(ApplicationContextHelper.getNextIdentity());
            getDao().insert(fromBean);
            return fromBean.getId();
        }
        List<LimsOutsourceSampleBean> inserts = new ArrayList<>();
        List<Long> productIds = Arrays.stream(productids.split(",")).filter(s -> !StringUtils.isBlank(s)).map(NumberUtils::parseLong).collect(Collectors.toList());
        LimsOutsourceApplyBean applyBean = limsOutsourceApplyService.selectByIdIfPresent(fromBean.getApplyId());
        if (applyBean != null) {
            List<LimsOutsourcersProductMainBean> osProducts = limsOutsourcersProductMainService.selectListByFilter(SearchFilter.instance().match("outsourcerId", applyBean.getOutsourcerId()).filter(MatchPattern.EQ));
            osProducts.stream().filter(osp -> productIds.contains(osp.getProductMainId())).collect(Collectors.toList()).forEach(osp -> {
                LimsOutsourceSampleBean insert = new LimsOutsourceSampleBean();
                insert.setId(ApplicationContextHelper.getNextIdentity());
                BeanUtils.copyProperties(fromBean, insert, "id", "productName", "productCode", "productId");
                insert.setProductId(osp.getProductMainId());
                insert.setProductCode(osp.getProductCode());
                insert.setProductName(osp.getProductName());
                inserts.add(insert);
            });
            if (!inserts.isEmpty()) {
                getDao().insert(inserts);
            }
        }
        return 0L;
    }

    @Override
    public JSONObject setResult(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        String testResult = wrapperBean.getParamValue("testResult");
        List<Long> ids = wrapperBean.parse(LimsOutsourceSampleBean.class).stream().map(LimsOutsourceSampleBean::getId).collect(Collectors.toList());
        if (ids.isEmpty()) {
            return req;
        }
        LimsOutsourceSampleBean update = new LimsOutsourceSampleBean();
        update.setTestResult(testResult);
        getDao().updateByIds(update, ids, "testResult");
        return req;
    }

    @Override
    public JSONObject insertMulti(RestJsonWrapperBean wrapperBean) {
        JSONObject req = new JSONObject();
        List<LimsOutsourceSampleBean> from = wrapperBean.parse(LimsOutsourceSampleBean.class);
        if (from.isEmpty() || from.get(0).getApplyId() == null) {
            return req;
        }
        from.forEach(f -> f.setId(ApplicationContextHelper.getNextIdentity()));
/*        LimsOutsourceApplyBean applyBean = limsOutsourceApplyService.selectByIdIfPresent(from.get(0).getApplyId());
        if (applyBean == null || applyBean.getId() == null) {
            return req;
        }
        List<LimsOutsourcersProductMainBean> osProducts = limsOutsourcersProductMainService.selectListByFilter(SearchFilter.instance().match("outsourcerId", applyBean.getOutsourcerId()).filter(MatchPattern.EQ));
        List<LimsOutsourceSampleBean> inserts = new ArrayList<>();
        from.forEach(fromBean -> {
            String productids = fromBean.getExt$Item("productids");
            if (StringUtils.isBlank(productids)) {
                fromBean.setId(ApplicationContextHelper.getNextIdentity());
                inserts.add(fromBean);
            } else {
                List<Long> productIds = Arrays.stream(productids.split(",")).filter(s -> !StringUtils.isBlank(s)).map(NumberUtils::parseLong).collect(Collectors.toList());
                osProducts.stream().filter(osp -> productIds.contains(osp.getProductMainId())).collect(Collectors.toList()).forEach(osp -> {
                    LimsOutsourceSampleBean insert = new LimsOutsourceSampleBean();
                    insert.setId(ApplicationContextHelper.getNextIdentity());
                    BeanUtils.copyProperties(fromBean, insert, "id", "productName", "productCode", "productId");
                    insert.setProductId(osp.getProductMainId());
                    insert.setProductCode(osp.getProductCode());
                    insert.setProductName(osp.getProductName());
                    inserts.add(insert);
                });
            }
        });*/
/*        if (!inserts.isEmpty()) {
            getDao().insert(inserts);
        }*/
        getDao().insert(from);
        return req;
    }
}
